# 多线程

# # 线程子函数
# import threading
# from time import sleep


# def test0(name:str, times_ms:int = 1000):
#     while True:
#         print(f"{name}执行中...")
#         sleep(times_ms*0.001)

# t = threading.Thread(target=test0, args=("日志模块",200))
# t.start()
# t.join() #等待结束

# # 继承方式
# import threading
# import time

# class MyThread(threading.Thread):
#     def __init__(self,name:str, times_ms:int = 1000):
#         super().__init__(name=name)
#         self.times_ms = times_ms

#     def run(self):
#         while True:
#             print(f"{self.name}执行中...")
#             time.sleep(self.times_ms*0.001)

# t = MyThread("类继承 日志模块", 2000)

# t.start()
# t.join()

import threading
import time

# 共享资源
balance = 0
lock = threading.Lock()

def deposit(amount):
    global balance
    for _ in range(10):
        with lock:  # 使用上下文管理器自动加锁/解锁
            temp = balance
            time.sleep(0.001)
            balance = temp + amount
        # lock.acquire()  # 手动加锁
        # 关键操作...
        # lock.release()  # 手动解锁

# 创建线程
t1 = threading.Thread(target=deposit, args=(1,))
t2 = threading.Thread(target=deposit, args=(1,))

t1.start()
t2.start()
t1.join()
t2.join()

print(f"最终余额: {balance}")  # 正确应为20 (10 * 1 + 10 * 1)